﻿using Microsoft.WindowsAzure.Storage.Blob;
using PetkaWebDav.Server.Framework.BaseClasses;
using PetkaWebDav.Server.Framework.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.Core.WebDav.Handlers
{
    /// <summary>
    /// Custom implementation example for DavPut.
    /// </summary>
    public sealed class DavPut : DavPutBase
    {
        public DavPut()
        {
        }

        protected override async Task OnProcessDavRequest(EventArgs e)
        {
            BlobItem _blob = await RequestWrapper.DownloadBlobAttributes(this.GetRelativeRequestPath());

            if (_blob == null)
                base.AbortRequest(ServerResponseCode.NotFound);
            else
            {
                if (false) //(!base.OverwriteExistingResource)
                {
                    //Check to see if the resource already exists
                    if (_blob != null)
                        base.AbortRequest(DavPutResponseCode.Conflict);
                    else
                        await SaveFile(_blob);
                }
                else
                    await SaveFile(_blob);
            }
        }

        private async Task SaveFile(BlobItem _blob)
        {
            byte[] _requestInput = base.GetRequestInput();

            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(_requestInput, 0, _requestInput.Length);
                stream.Position = 0;
                await RequestWrapper.UploadBlob(_blob.Path, stream);
            }
        }
    }
}
